<template>
  <el-form :model="form" label-width="0" ref="form" :rules="rules">
    <el-form-item prop="username">
      <el-input v-model="form.username" :maxlength="32" placeholder="手机号码 / 邮箱"/>
    </el-form-item>
    <el-form-item prop="password">
      <el-input type="password" :maxlength="32" v-model="form.password" placeholder="登陆密码, 3-32位"/>
    </el-form-item>
    <el-form-item prop="code">
      <el-input type="code" :maxlength="6" v-model="form.code" placeholder="请输入验证码">
        <!--suppress HtmlUnknownTarget -->
        <img class="imageCode" alt="imageCode" slot="append" :src="imageCodeUrl" @click="freshImageCode"/>
      </el-input>
    </el-form-item>
    <el-button type="primary" @click="login('form')" :loading="loading"
               :disabled="loading" class="btn" style="width: 100%">
      {{loginButtonMessage}}
    </el-button>
    <p v-if="showToRegister" class="register-link">
      Don’t have an account, <span class="link" @click="toRegister">register now!</span>
    </p>
  </el-form>
</template>

<script>
import regexp from '@/utils/RegexpUtils'
import { loginByPass } from '@/api/ApiUser'
import sysConfig from '@/config/sysConfig'

export default {
  name: 'FormLogin',
  props: ['showToRegister'],
  data: () => {
    const validUsername = (rule, value, callback) => {
      if (value.indexOf('@') !== -1) {
        if (!regexp.validEmail(value)) {
          callback(new Error('不是合法的邮箱地址'))
        }
      } else {
        if (!regexp.validPhone(value)) {
          callback(new Error('不是合法的手机号码'))
        }
      }
      return callback()
    }
    return {
      loading: false,
      imageCodeFresh: new Date().getTime(),
      form: {
        username: '',
        password: '',
        code: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 32, message: '长度在 3 到 32 个字符', trigger: 'blur' },
          { validator: validUsername, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 32, message: '长度在 3 到 32 个字符', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '验证码不能为空', trigger: 'blur' },
          { pattern: '^[0-9a-zA-Z]{4,6}$', message: '验证码是4-6个数字或字母组成的字符串', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    loginButtonMessage () {
      return this.loading ? 'Logging' : 'Login'
    },
    imageCodeUrl () {
      return sysConfig.baseUrl + '/middle-user/user/imageCode?key=login&temp=' + this.imageCodeFresh + ')'
    }
  },
  methods: {
    toRegister () {
      this.$emit('toRegister')
    },
    login (formName) {
      const vm = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          vm.loading = true
          loginByPass(vm.form.username, vm.form.password, vm.form.code, () => {
            this.$emit('success')
            vm.$message.success('登陆成功')
          }, () => {
            this.freshImageCode()
          }, () => {
            vm.loading = false
          })
        }
      })
    },
    freshImageCode () {
      this.imageCodeFresh = new Date().getTime()
    }
  },
  mounted () {
    this.freshImageCode()
  }
}
</script>

<!--suppress CssUnusedSymbol -->
<style>
  .el-input-group__append{
    padding: 2px 2px 0;
  }
</style>

<style lang="scss" scoped>

  .register-link{
    margin-top: 20px;
    color: #777777;
    user-select: none;

    .link{
      color: #444444;
      cursor: pointer;
      margin-left: 4px;
    }

    .link:hover{
      color:darksalmon
    }

  }

  .imageCode{
    cursor: pointer;
    width: 80px;
    height: 32px;
    display: inline-block;
    background-size: 100% 100%;
  }
</style>
